<template>
  <cascader
    class="m-address-cascader"
    :disabled="disabled"
    :value="value"
    :options="optionsTree"
    :placeholder="placeholder"
    :label.sync="label"
    @change="handleChange"/>
</template>

<script>
import Cascader from './Cascader'
export default {
  components: {
    Cascader
  },
  props: {
    ...Cascader.props,
    grade: {
      type: Number,
      default: 3
    },
    placeholder: {
      type: String,
      default: '请选择地区'
    },
    addressTree: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    let label = []
    let optionsTree = []
    this._getAreaJSON().then(areaJSON => {
      this.$$areaJSON = areaJSON
      if (this.addressTree.length) {
        this.optionsTree = this.addressTree // 使用传递渲染好的地址数据
      } else {
        this._initAddressData(areaJSON) // 使用默认初始化地址数据
      }
    })
    return {
      label,
      optionsTree
    }
  },
  methods: {
    _getAreaJSON () {
      return new Promise((resolve) => {
        require.ensure([], (r) => {
          let areaJSON = require('areaJSON')
          resolve(areaJSON)
        })
      })
    },
    _initAddressData (areaJSON) {
      // 初始化地址数据
      let result = []
      areaJSON.province.forEach(p => {
        let city = []
        if (areaJSON.city[p.areaId] && this.grade > 1) {
          areaJSON.city[p.areaId].forEach(c => {
            let area = []
            if (areaJSON.area[c.areaId] && this.grade > 2) {
              areaJSON.area[c.areaId].forEach(a => {
                a.parentId === c.areaId && area.push({
                  value: a.areaId,
                  label: a.title
                })
              })
            }
            let cityObject = {
              value: c.areaId,
              label: c.title
            }
            if (this.grade > 2 && area.length) {
              cityObject.children = area
            }
            city.push(cityObject)
          })
        }
        result.push({
          value: p.areaId,
          label: p.title,
          children: this.grade > 1 ? city : null
        })
      })
      this.optionsTree = result
    },
    handleChange (value) {
      this.$emit('input', value).$emit('change', value).$emit('update:label', this.label)
    }
  }
}

</script>

<style lang="scss">
  .m-address-cascader{
    color:inherit;
  }
</style>
